<template>
  <el-dialog v-model="dialogInfo.visible" :title="dialogInfo.title" :width="dialogInfo.width" align-center>
    <el-form ref="formRef" label-position="left" :model="formModel" :rules="formRules" label-width="120px">
        <h2 class="t-c text-white"> {{ infoData._semester?.semesterName }} 第{{ infoData?._week }}周 {{ infoData._room?.name }} {{baseDate.startOf('isoWeek').add(infoData?._index,'d').format("dddd")}} </h2>
        <div><h2 class="t-c text-white">
          <template v-for="item of infoData?._lessons">第{{ item.id }}节</template>
        </h2></div>
      <el-row>
        <el-col :sm="24">
          <el-form-item label="添加课程" prop="degreeType">
            <el-col :span="8">
                <el-select clearable class="w100 pr-3" style="box-sizing: border-box;" v-model="formModel.AcademyId" placeholder="请选择学院" autocomplete="off" @change="getMajorList">
                  <el-option v-for="item in academyOption" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
            </el-col>
            <el-col :span="8">
              <el-select clearable :disabled="!formModel.AcademyId" class="w100 pr-3" style="box-sizing: border-box;" v-model="formModel.MajorId" placeholder="请选择专业" autocomplete="off" @change="getCourseList">
                <el-option v-for="item in majorOption" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select clearable class="w100" :disabled="!formModel.MajorId" v-model="formModel.CourseId" placeholder="请选择课程" autocomplete="off">
                <el-option v-for="item in courseOption" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-col>
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="教师姓名" prop="TeacherId">
            <el-select
                v-model="formModel.TeacherId"
                style="width: 240px"
                filterable
                remote
                :remote-method="getTeacherList"
                clearable
                :options="teacherOption"
                :loading="teacherLoading"

                placeholder="请输入搜索教师"
            >
             <el-option v-for="item in teacherOption" :key="item.Id" :label="item.Academy.name+' - ' + item.name" :value="item.Id"></el-option>
            </el-select>
<!--            <el-select clearable class="w100" v-model="formModel.TeacherId" placeholder="请选择老师" autocomplete="off">-->
<!--              <el-option v-for="item in teacherOption" :key="item.id" :label="item.teacherName" :value="item.id"></el-option>-->
<!--            </el-select>-->
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="是否录播" prop="IsRecordTask">
            <el-radio-group v-model="formModel.IsRecordTask">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="是否直播" prop="IsLiveTask">
            <el-radio-group v-model="formModel.IsLiveTask">
              <el-radio v-for="item in liveTaskTypeOption" :label="Number(item.key)" :key="Number(item.key)">{{item.label}}</el-radio>
            </el-radio-group>
            <el-transfer  v-if="formModel.IsLiveTask === 1" class="mt-3" :titles="['请选择互动教室', '已选择']" v-model="formModel.interactRoom" :data="roomOption" :props="{key: 'id',label: 'Name'}" >
              <template #default="{ option }">
                <el-tooltip placement="top" :content="option.Building.Campus.Name +'-'+ option.Building.name +'-'+ option.Name">
                  <span>{{ option.Name }} - {{ option.Building.name }}{{ option.Building.Campus.Name }}</span>
                </el-tooltip>
              </template>
            </el-transfer>
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="是否启用" prop="enable">
            <el-radio-group v-model="formModel.enable">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">不启用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="info" plain @click="onCancel()">取消</el-button>
        <el-button type="primary" @click="onSubmit()">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
/**
 * 管理员编辑组件
 */
import {h,computed, ref} from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import { getNewObj } from '@/utils/EsCommon';
import {liveTaskParams, liveTaskTypeList, taskForm} from '@/apis/model/LiveTaskModel';
import moment from "moment/moment";
moment.locale('zh-cn', {
  weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
});



// ======================================================
//                      变量声明
// ======================================================

// emit
const emit = defineEmits(['success']);
// 表单数据
const formAttrs = getNewObj(taskForm());

const formModel = ref(Object.assign({}, formAttrs));
// 弹窗信息
const dialogInfo = ref({
  visible: false,
  title: '',
  width: '730px',
})
// 表单组件的引用实例
const formRef = ref(null);
const infoData = ref({})
// 选项数据
const liveTaskTypeOption = ref(liveTaskTypeList);
const academyOption = ref([]);
const majorOption = ref([]);
const courseOption = ref([]);
const teacherLoading = ref(false);
const teacherOption = ref([]);
const campusOption = ref([]);
const buildingOption = ref([]);
const roomOption = ref([]);

const baseDate = computed(()=>{
  const sv = infoData?._semester ||{}
  return  moment(sv.startTime).add(infoData?._week - 1,'week')
})
// 表单校验规则
const formRules = ref({
  name: [{ required: true, trigger: "blur", message: "请输入教室名称" }],
})

// ======================================================
//                      点击操作
// ======================================================

// 点击提交按钮
const onSubmit =  () => {
  formRef.value.validate((valid, fields) => {
    if (!valid) {
      console.log('表单校验失败：', fields);
      return;
    }
    onSendTest().then(()=>{
      if(formModel.value.IsRecordTask){
        onSendRecordTask()
      }
      if(formModel.value.IsLiveTask){
        onSendLiveTask()
      }
    })

  })
}
const onSendTest = async ()=>{
  const form = JSON.parse(JSON.stringify(formModel.value))
 return  new Promise( async (resolve, reject)=>{
   let lives = []
   let liveText = ''
   let records = []
   let recordText = ''
   if(formModel.value.IsLiveTask){
    await EsAjax.post(ApiUrls.liveTaskTest,{
       "RoomId" : form.RoomId,
       "ClassDay": form.ClassDay,
       "ClassId":form.ClassId,
     }).then((_res)=> {
       if (_res.data.code !== 200) {
         liveText = '直播'
         lives = _res.data.data||[]
       }
     }).catch(err => {
      reject(false)
      ElMessage.error('网络错误：' + err.message);
     })
   }

   if(formModel.value.IsRecordTask){
    await EsAjax.post(ApiUrls.recordTaskTest,{
       "RoomId" : form.RoomId,
       "ClassDay": form.ClassDay,
       "ClassId":form.ClassId,
     }).then((res)=> {
       if (res.data.code !== 200) {
         recordText = '录播'
         records = res.data.data||[]
       }
     }).catch(err => {
        reject(false)
       ElMessage.error('网络错误：' + err.message);
     })
   }

   if(lives.concat(records).length){
     let message = ''
     const node = [h('p',null,'已有该时段任务')]
     if(lives.length){
           node.push( h('p', {  }, '直播：' +  lives.map(item=>(item.startTime + '-' + item.endTime)).join(' | ')))
     }
     if(records.length){
       node.push( h('p', {}, '录播：' +  records.map(item=>(item.startTime + '-' + item.endTime)).join(' | ')))
     }
     ElMessageBox.alert( h('div', null, node))
     reject(false)
   }else{
     resolve(true)
   }
  })
}
const onSendRecordTask=  ()=>{
  let url = formModel.value.id > 0 ? ApiUrls.recordTaskChange : ApiUrls.recordTaskAdd;
  const form = JSON.parse(JSON.stringify(formModel.value))
  console.log(form)

    EsAjax.post(url, form).then(res => {
      if (res.data.code !== 200) {
        ElMessage.warning(res.data.msg);
        return;
      }
      dialogInfo.value.visible = false;
      ElMessage.success('提交成功');
      emit('success');
    }).catch(err => {
      ElMessage.error('网络错误：' + err.message);
    })
}
const onSendLiveTask=  ()=>{
  let url = formModel.value.id > 0 ? ApiUrls.liveTaskChange : ApiUrls.liveTaskAdd;
  const form = JSON.parse(JSON.stringify(formModel.value))
  console.log(form)
  if(form.IsLiveTask === 1){
    form.liveTaskRole = 1
    form.interactRoom =  form.interactRoom.join(',')
  }
    EsAjax.post(url, form).then(res => {
      if (res.data.code !== 200) {
        ElMessage.warning(res.data.msg);
        return;
      }
      dialogInfo.value.visible = false;
      ElMessage.success('提交成功');
      emit('success');
    }).catch(err => {
      ElMessage.error('网络错误：' + err.message);
    })

}

// 点击取消按钮
const onCancel = () => {
  formModel.value = Object.assign({}, formAttrs);
  formRef.value.resetFields();
  dialogInfo.value.visible = false;
  infoData.value = {}
}
// ======================================================
//                      处理事件
// ======================================================


// 加载数据
const show = async (id, title, item = null, width = '730px') => {
  dialogInfo.value.title = title;
  dialogInfo.value.width = width;
  dialogInfo.value.visible = true;
  infoData.value = item;
  // 加载详情数据
  formAttrs.ClassId = infoData.value._lessons.map(item=>{
    return item.id
  }).join(',')
  formAttrs.ClassDay = baseDate.value.startOf('isoWeek').add(infoData?.value._index,'d').format("YYYY-MM-DD")
  formAttrs.RoomId = infoData.value._room.id
  formAttrs.RecordIp = infoData.value._room.recordingIp
  formModel.value = Object.assign({}, formAttrs)
  if (item._course.id) {
    formModel.value = Object.assign({ ...formAttrs });
  }
  getAcademyList();
  // getCampusList();
  // getBuildingList();
  getRoomList();
  // getMajorList();
  // getCourseList();
  // getTeacherList();
}
const getAcademyList = () => {
  EsAjax.post(ApiUrls.academyList, { params: {} }).then(res => {
    console.log(res)

    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    let { list } = res.data.data
    academyOption.value = list;
  }).catch(err => {
    ElMessage.error(err.message);
  })
}

const getMajorList = () => {
  if(formModel.value.AcademyId) {
    EsAjax.post(ApiUrls.majorList, {AcademyId: formModel.value.AcademyId}).then(res => {
      if (res.data.code !== 200) {
        ElMessage.warning(res.data.msg);
        return;
      }
      let {list} = res.data.data
      majorOption.value = list;
    }).catch(err => {
      ElMessage.error(err.message);
    })
  }
  formModel.value.MajorId = null
  formModel.value.CourseId = null
  majorOption.value = [];
  courseOption.value = [];
}
const getCourseList = () => {
  if(formModel.value.MajorId && formModel.value.AcademyId){
    EsAjax.post(ApiUrls.courseList, { AcademyId:formModel.value.AcademyId,MajorId:formModel.value.MajorId}).then(res => {
      console.log(res)
      if (res.data.code !== 200) {
        ElMessage.warning(res.data.msg);
        return;
      }
      let { list } = res.data.data
      courseOption.value = list;
    }).catch(err => {
      ElMessage.error(err.message);
    })
  } else{
    formModel.value.CourseId = null
    courseOption.value = [];
  }

}
const getCampusList = () => {
  EsAjax.post(ApiUrls.campusList, { params: {} }).then(res => {
    console.log(res)
    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    let { list } = res.data.data
    campusOption.value = list;
  }).catch(err => {
    ElMessage.error(err.message);
  })
}
const getBuildingList = () => {
  EsAjax.post(ApiUrls.buildingList, { params: {} }).then(res => {
    console.log(res)

    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    let { list } = res.data.data
    buildingOption.value = list;
  }).catch(err => {
    ElMessage.error(err.message);
  })
}
const getRoomList = () => {
  EsAjax.post(ApiUrls.roomList, {  }).then(res => {
    console.log(res)

    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    let { list } = res.data.data
    roomOption.value = list;
  }).catch(err => {
    ElMessage.error(err.message);
  })
}
const getTeacherList = (name) => {
  if(name){
  teacherLoading.value = true
  EsAjax.post(ApiUrls.teacherList, { role: 1,realName:name }).then(res => {
    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    let { list, count } = res.data.data
    teacherOption.value = list;
  }).catch(err => {
    ElMessage.error(err.message);
  }).finally(()=>{
    teacherLoading.value = false
  })
  }else{
    teacherOption.value = [];
  }
}

defineExpose({
  show
})
</script>

<style scoped>
</style>
